import {Component, OnInit, AfterContentInit, Injector} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {NzModalRef} from 'ng-zorro-antd/modal';
import {EmployeeServiceSvr} from '../../../../../services/employee.service';
import {DeptServiceSvr} from '../../../../../services/dept.service';
import {MyDepartment} from '../../../../../domains/mydepartment.domain';
import {Employee} from '../../../../../domains/employee.domain';
import {NzMessageService} from 'ng-zorro-antd/message';
import {CoreComponent} from 'pengesoft-ng-lib';

@Component({
  selector: 'app-roster-update',
  templateUrl: './roster-update.component.html',
  styleUrls: ['./roster-update.component.less']
})
export class RosterUpdateComponent extends CoreComponent implements OnInit, AfterContentInit {

  data: any;
  validateForm!: FormGroup;
  nzOptions: any[] | null = null;
  options: any[] | null = null;
  values: any[] | null = [];
  postingList: any[] | null = [];

  postingValue: string[] | null = null;
  optionList = [
    { label: '实习', value: '实习' },
    { label: '试用', value: '试用'},
    { label: '正式', value: '正式'},
    { label: '挂靠', value: '挂靠'},
    { label: '残疾', value: '残疾'}
  ];
  identifyCardList = [
    { label: '中国居民身份证', value: '中国居民身份证' },
    { label: '港澳台居民', value: '港澳台居民'},
  ];
  optionDegreeList = [
    { label: '高中', value: '高中' },
    { label: '大专', value: '大专'},
    { label: '本科', value: '本科'},
    { label: '研究生', value: '研究生'},
    { label: '博士', value: '博士'},
  ];
  optionPoliticalList = [
    { label: '无', value: '无' },
    { label: '共青团员', value: '共青团员'},
    { label: '党员（含预备党员）', value: '党员（含预备党员）'},
  ];
  date = null;
  selectedValue: any;
  identifyCardValue: any;
  degreeValue: any;
  politicalValue: any;
  employeeFormValue: any;
  choose = '';
  radioValue = '1';
  employee = new Employee();
  // tslint:disable-next-line:max-line-length
  sendRosterTableData: { skay: number; jobnumber: any; phone: any; sex: string; name: any; id: any; state: any; posting: any; department: any; age: any }[];


  constructor(private injector: Injector,
              private fb: FormBuilder,
              private modal: NzModalRef,
              private deptSvr: DeptServiceSvr,
              private employSvr: EmployeeServiceSvr,
              private message: NzMessageService) {
    super(injector);
  }

  ngOnInit(): void {
    this.selectedValue = this.data.state;
    this.validateForm = this.fb.group({
      name: [this.data.name, [Validators.required]],
      posting: [this.data.posting, [Validators.required]],
      jobNumber: [{value: this.data.jobnumber, disabled: 'true'}, [Validators.required]],
      age: [this.data.age, [Validators.required, this.numberValidator]],
      sex: [this.data.sex, [Validators.required]],
      phone: [this.data.phone, [Validators.required, this.numberValidator]],
      ces: [this.data.posting, [Validators.required]],
      identifyCard: [this.data.identifyCard, [Validators.required]],
      identifyId: [this.data.identifyId, [Validators.required, this.numberValidator]],
      school: [this.data.school, [Validators.required]],
      major: [this.data.major, [Validators.required]],
      time: [this.data.time, [Validators.required]],
      degree: [this.data.degree, [Validators.required]],
      political: [this.data.political, [Validators.required]],
      native: [this.data.native, [Validators.required]],
      emergencyPerPhone: [this.data.emergencyPerPhone, [Validators.required]],
      emergencyPer: [this.data.emergencyPer, [Validators.required]],
      employeeForm: [this.data.employeeForm, [Validators.required]],
      cardNum: [this.data.cardNum, [Validators.required]],
      IDPlace: [this.data.IDPlace, [Validators.required]],
      NowPlace: [this.data.NowPlace, [Validators.required]],
    });
    // @ts-ignore
    this.postingValue = this.data.jobNumber;
    this.values = [this.data.department] ;
    this.deptSvr.getAllMyDepartment().then(res => {
      this.options = this.traversal([res] as unknown as MyDepartment[]);
      this.nzOptions = this.options;
    });
  }

  // 遍历
  traversal(arr: MyDepartment[]): any{
    return arr.map((item => {
      return {
        value: item.NodeId,
        label: item.DeptName,
        isLeaf: (item.ChildDepartment as unknown as MyDepartment[]).length === 0,
        // tslint:disable-next-line:max-line-length
        children: (item.ChildDepartment as unknown as MyDepartment[]).length === 0 ? [] : this.traversal(item.ChildDepartment as unknown as MyDepartment[])
      };
    }));

  }

  // 校验数字  -- 非0的正整数
  numberValidator(value): any{
    const myreg = /^\d+$/;
    const valid = myreg.test(value.value);
    return valid ? null : {identifyId: true, age: true};
  }

  ngAfterContentInit(): void {
  }

  // 确定按钮
  handleOk(e: any, validateForm): void {
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    const sex = validateForm.value.Sex === '女' ? 1 : 0;

    this.employee.Id = this.data.id;
    this.employee.JobId = validateForm.value.posting.value;
    this.employee.Name = validateForm.value.name;
    this.employee.Sex = sex;
    this.employee.EmployForm = validateForm.value.employeeForm.value;
    this.employee.StateId = '在职';
    this.employee.GraduatedSchool = validateForm.value.school;
    this.employee.StudyMajor = validateForm.value.major;
    this.employee.EducationLevel = validateForm.value.degree.degree;
    this.employee.GraduatedTime = validateForm.value.time;
    this.employee.NativePlace = validateForm.value.native;
    this.employee.IDCard = validateForm.value.identifyId;
    this.employee.Age = validateForm.value.age;
    this.employee.Phone = validateForm.value.phone;
    this.employee.EmergencyPeople = validateForm.value.emergencyPer;
    this.employee.EmergencyContact = validateForm.value.emergencyPerPhone;
    this.employee.IDPlace = validateForm.value.IDPlace;
    this.employee.NowPlace = validateForm.value.NowPlace;
    this.employee.Politic = validateForm.value.political.value;
    this.employee.CardNum = validateForm.value.cardNum;
    if (this.validateForm.valid) {
      this.employSvr.updateEmployee(this.employee).then(res => {
        if (res === 1) {
          this.message.success('修改成功！');
        }else {
          this.message.error('修改失败！');
        }
        // tslint:disable-next-line:no-shadowed-variable
        this.employSvr.myGetAllEmployDto().then( res => {
          this.sendRosterTableData = this.dealDate(res);
          this.modal.destroy(this.sendRosterTableData);
        });
      });
    }
  }

  // 取消按钮
  handleCancel(e: MouseEvent): void {
    this.modal.destroy();
  }

  changeNzOptions(): void {
    this.nzOptions = this.options;
  }

  // 部门变化
  onChanges(values: any): void {
    this.deptSvr.getAllJobByDept(values[values.length - 1]).then(res => {
      this.postingList = res.map(item => {
        return {
          label: item.JobName, value: item.Id ,
        };
      });
    });
  }

  // 改变下拉框的值
  changeOptionValue(value: { label: string; value: string; }): void {
  }

  // 时间选择变化
  onChange(result: Date): void {
  }

  // 数据的处理
  dealDate(res): any{
    return res.map((items, index) => {
      const sex = items.Employee.sex === 0 ? '男' : '女';
      return {
        id: items.Employee.Id,
        skay: index + 1,
        posting: items.JobName,
        department: items.DeptName,
        jobnumber: items.Employee.Id,
        age: items.Employee.Age,
        sex,
        phone: items.Employee.Phone,
        state: items.Employee.StateId,
        name: items.Employee.Name,
        identifyCard: items.Employee.IDCard,
        identifyId: items.Employee.IDCard,
        school: items.Employee.GraduatedSchool,
        major: items.Employee.StudyMajor,
        degree: items.Employee.EducationLevel,
        political: items.Employee.Politic,
        native: items.Employee.NativePlace,
        emergencyPerPhone: items.Employee.EmergencyContact,
        emergencyPer: items.Employee.EmergencyPeople,
        employeeForm: items.Employee.EmployForm,
        cardNum: items.Employee.CardNum,
        IDPlace: items.Employee.IDPlace,
        NowPlace: items.Employee.NowPlace,
      };
    });
  }

}
